package com.example.videoeditor.controller;

import com.example.videoeditor.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Controller
public class VideoController {

    @Autowired
    private VideoService videoService;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/upload")
    public String uploadVideo(@RequestParam("files") MultipartFile[] files,
                              @RequestParam("adTime") double adTime, Model model) {
        List<String> messages = new ArrayList<>();
        List<String> downloadLinks = new ArrayList<>();

        if (files.length == 0) {
            messages.add("文件不能为空");
            model.addAttribute("messages", messages);
            return "index";
        }

        try {
            // 创建上传目录
            File uploadDir = new File("uploads");
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            for (MultipartFile file : files) {
                // 保存上传的文件
                String filePath = uploadDir.getAbsolutePath() + File.separator + file.getOriginalFilename();
                File dest = new File(filePath);
                file.transferTo(dest);

                // 处理视频
                String result = videoService.processVideo(dest, adTime);

                // 获取处理后文件的路径
                String processedFileName = dest.getName().substring(0, dest.getName().lastIndexOf('.')) + "_yx.mp4";
                String processedFilePath = uploadDir.getAbsolutePath() + File.separator + processedFileName;

                messages.add(result);
                if (result.contains("处理完成")) {
                    downloadLinks.add("/download/" + processedFileName);
                }
            }
        } catch (IOException | InterruptedException e) {
            messages.add("处理视频时出错: " + e.getMessage());
        }

        model.addAttribute("messages", messages);
        model.addAttribute("downloadLinks", downloadLinks);

        return "index";
    }

    @GetMapping("/download/{fileName:.+}")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get("uploads").resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException ex) {
            return ResponseEntity.badRequest().build();
        }
    }
}
